<template>
  <ContentWrap>
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
        v-model="original"
        placeholder="请输入原文搜索"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
    </div>

    <div ref="tableContainer" class="table-container">
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        style="width: 100%"
        height="calc(100vh - 250px)"
      >
        <el-table-column prop="original" label="原文" width="180" fixed="left">
          <template #default="scope">
            <div style="padding: 0 8px">
              {{ scope.row.original }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="lang in languages"
          :key="lang.value"
          :label="lang.label"
          width="150"
        >
          <template #default="scope">
            <div
              @click="handleCellClick(scope.$index, lang.value)"
              style="min-height: 32px; padding: 0 8px; cursor: pointer"
            >
              {{ scope.row.translations[lang.value] || '点击编辑' }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageIndex"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑弹出层 -->
    <el-dialog v-model="dialogVisible" title="编辑翻译" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="原文">
          <div>{{ currentRow?.original }}</div>
        </el-form-item>
        <el-form-item :label="currentLang?.label">
          <el-input
            v-model="editForm.translation"
            type="textarea"
            :rows="4"
            placeholder="请输入翻译内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { ref, onMounted, nextTick } from 'vue'
import { languages } from '../../../config/language'
import { getListApi, editListApi } from '@/api/translate'
import type { TranslationItem, TranslationListResponse } from '@/api/translate/types'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

interface TranslationData {
  id: string
  original: string
  translations: {
    zh?: string
    en?: string
    fr?: string
    de?: string
    es?: string
    ru?: string
    ja?: string
    it?: string
    ko?: string
    pt?: string
    ar?: string
    vn?: string
  }
}

const tableData = ref<TranslationData[]>([])
const dialogVisible = ref(false)
const currentRow = ref<TranslationData | null>(null)
const currentLang = ref<{ value: string; label: string } | null>(null)
const editForm = ref({
  translation: ''
})

// 分页相关
const pageIndex = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索相关
const original = ref('')

const tableContainer = ref<HTMLElement | null>(null)
const tableRef = ref()

const handleCellClick = (rowIndex: number, columnKey: string) => {
  const rowData = tableData.value[rowIndex]
  if (!rowData) return

  currentRow.value = rowData
  currentLang.value = languages.find((lang) => lang.value === columnKey) || null
  editForm.value.translation = rowData.translations[columnKey] || ''
  dialogVisible.value = true
}

const handleSave = async () => {
  if (!currentRow.value || !currentLang.value) return

  const oldValue = currentRow.value.translations[currentLang.value.value]
  const newValue = editForm.value.translation

  // 如果值没有改变，直接关闭弹窗
  if (oldValue === newValue) {
    dialogVisible.value = false
    return
  }

  try {
    // 构造请求参数
    const params = {
      content: {
        [currentRow.value.id]: {
          [currentLang.value.value]: newValue
        }
      }
    }

    // 调用编辑接口
    const response = await editListApi(params)
    if (response.code === 0) {
      // 更新本地数据
      currentRow.value.translations[currentLang.value.value] = newValue
      ElMessage.success('修改成功')
      dialogVisible.value = false
    } else {
      ElMessage.error('修改失败')
    }
  } catch (error) {
    ElMessage.error('修改失败')
    console.error('Failed to update translation:', error)
  }
}

// 滚动到顶部
const scrollToTop = () => {
  if (tableRef.value) {
    tableRef.value.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 处理页码改变
const handleCurrentChange = (val: number) => {
  pageIndex.value = val
  fetchData()
  nextTick(() => {
    scrollToTop()
  })
}

// 处理每页条数改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  pageIndex.value = 1 // 重置到第一页
  fetchData()
  nextTick(() => {
    scrollToTop()
  })
}

// 处理搜索
const handleSearch = () => {
  pageIndex.value = 1 // 重置到第一页
  fetchData()
  nextTick(() => {
    scrollToTop()
  })
}

const fetchData = async () => {
  try {
    const response = await getListApi({
      pageIndex: pageIndex.value,
      pageSize: pageSize.value,
      original: original.value // 修改参数名
    })
    if (response.code === 0 && response.data) {
      // Transform the data to match our table structure
      const data = response.data as unknown as {
        list: { [key: string]: TranslationItem }
        total: number
      }
      const { list, total: totalCount } = data
      tableData.value = Object.entries(list).map(([key, value]) => {
        const item = value as TranslationItem
        return {
          id: key,
          original: item.original,
          translations: {
            zh: item.zh,
            en: item.en,
            fr: item.fr,
            de: item.de,
            es: item.es,
            ru: item.ru,
            ja: item.ja,
            it: item.it,
            ko: item.ko,
            pt: item.pt,
            ar: item.ar,
            vn: item.vn
          }
        }
      })
      // 更新总数
      total.value = totalCount
    }
  } catch (error) {
    console.error('Failed to fetch translation data:', error)
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container {
  display: flex;
  margin-top: 20px;
  justify-content: flex-start;
}

.search-container {
  display: flex;
  margin-bottom: 16px;
  gap: 12px;
  align-items: center;
}

.table-container {
  height: calc(100vh - 250px);
  overflow-y: auto;
}
</style>
